﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;

public class PictureLogicScript : MonoBehaviour {
    private static PictureLogicScript sInstance;
    public static int ImageIndex = 1;
    public static int MaxImageIndex = 2;

    private List<Texture2D> mTextureList = new List<Texture2D>();
    private List<Texture2D> mErrorTextureList = new List<Texture2D>();
    private List<Sprite> mErrorSpriteList = new List<Sprite>();

    private Sprite mChoosenSprite;

    void Awake()
    {
        GameObject.DontDestroyOnLoad(this.gameObject);
    }

	// Use this for initialization
	void Start () {
		
	}
	
	// Update is called once per frame
	void Update () {
		
	}

    public static void Create()
    {
        if (sInstance == null)
        {
            GameObject gameObject = GameObject.Find("PictureLogic");
            if (gameObject == null)
            {
                gameObject = new GameObject();
                gameObject.name = "PictureLogic";
                sInstance = gameObject.AddComponent<PictureLogicScript>();
            }
            else
            {
                sInstance = gameObject.GetComponent<PictureLogicScript>();
            }
            sInstance.StartLoadPictures();
        }
    }

    public static PictureLogicScript sGetInstance()
    {
        Create();
        return sInstance;
    }

    public void SetChooseSprite(Sprite sprite)
    {
        mChoosenSprite = sprite;
    }

    public Sprite GetSprite()
    {
        return mChoosenSprite;
    }

    IEnumerator LoadPictures()
    {
        //loadCorrect
        string path = Application.streamingAssetsPath + "/Pictures/";
        int successCount = 0;
        for (int i = 1; i <= 10; i++)
        {
            string filePath = path + i;
            try
            {
                if (File.Exists(filePath + ".jpg"))
                {
                    filePath = filePath + ".jpg";
                }
                else if (File.Exists(filePath + ".png"))
                {
                    filePath = filePath + ".png";
                }
                else if (File.Exists(filePath + ".bmp"))
                {
                    filePath = filePath + ".bmp";
                }
                if (File.Exists(filePath))
                {
                    Debug.Log("load : " + filePath);
                    //创建文件读取流
                    FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
                    fileStream.Seek(0, SeekOrigin.Begin);
                    //创建文件长度缓冲区
                    byte[] bytes = new byte[fileStream.Length];
                    //读取文件
                    fileStream.Read(bytes, 0, (int)fileStream.Length);
                    //释放文件读取流
                    fileStream.Close();
                    fileStream.Dispose();
                    fileStream = null;

                    //创建Texture
                    int width = 360;
                    int height = 360;
                    Texture2D texture = new Texture2D(width, height);
                    texture.LoadImage(bytes);
                    mTextureList.Add(texture);
                    successCount++;
                }
            }
            catch(Exception e){

            }            
        }
        MaxImageIndex = successCount;

        //loadError
        path = Application.streamingAssetsPath + "/Pictures/Error/";
        for (int i = 1; i <= 10; i++)
        {
            string filePath = path + i;
            try
            {
                if (File.Exists(filePath + ".jpg"))
                {
                    filePath = filePath + ".jpg";
                }
                else if (File.Exists(filePath + ".png"))
                {
                    filePath = filePath + ".png";
                }
                else if (File.Exists(filePath + ".bmp"))
                {
                    filePath = filePath + ".bmp";
                }
                if (File.Exists(filePath))
                {
                    Debug.Log("load : " + filePath);
                    //创建文件读取流
                    FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
                    fileStream.Seek(0, SeekOrigin.Begin);
                    //创建文件长度缓冲区
                    byte[] bytes = new byte[fileStream.Length];
                    //读取文件
                    fileStream.Read(bytes, 0, (int)fileStream.Length);
                    //释放文件读取流
                    fileStream.Close();
                    fileStream.Dispose();
                    fileStream = null;

                    //创建Texture
                    int width = 45;
                    int height = 45;
                    Texture2D texture = new Texture2D(width, height);
                    texture.LoadImage(bytes);
                    mErrorTextureList.Add(texture);
                    Sprite errorSprite = Sprite.Create(texture, new Rect(0f, 0f, texture.width, texture.height), Vector2.zero);
                    mErrorSpriteList.Add(errorSprite);
                }
            }
            catch (Exception e)
            {

            }
        }
        yield return 0;
    }

    public void StartLoadPictures()
    {
        StartCoroutine(LoadPictures());
    }

    public Texture2D GetTexture()
    {
        if (ImageIndex > 0)
        {
            if (mTextureList.Count >= ImageIndex)
            {
                return mTextureList[ImageIndex - 1];
            }
            else
            {
                ImageIndex = 1;
                return mTextureList[ImageIndex - 1];

            }
        }
        else
        {
            //maybe camera
            return null;
        }
    }

    public Sprite[] GetCorrectSprite()
    {
        Sprite[] spriteArray = new Sprite[PictureResultScript.RESULT_WIDTH * PictureResultScript.RESULT_HEIGHT];
        Texture2D texture = GetTexture();
        Debug.Log(texture.height + " " + texture.width + "  " + texture.name);
        for(int i = 0;i < PictureResultScript.RESULT_HEIGHT;i++)
        {
            for (int j = 0; j < PictureResultScript.RESULT_WIDTH; j++)
            {
                float offsetX = j * 1f / PictureResultScript.RESULT_WIDTH * texture.width;
                float offsetY = (PictureResultScript.RESULT_HEIGHT - i - 1) * 1f / PictureResultScript.RESULT_HEIGHT * texture.height;
                //offsetY = 0;
                Debug.Log(offsetX + "   " + offsetY);
                spriteArray[i * PictureResultScript.RESULT_HEIGHT + j] = Sprite.Create(texture, new Rect(offsetX, offsetY, texture.width / PictureResultScript.RESULT_WIDTH, texture.height / PictureResultScript.RESULT_HEIGHT), Vector2.zero);
            }
        }
        return spriteArray;
    }

    public Sprite GetErrorSprite()
    {
        if (mErrorSpriteList.Count > 0)
        {
            return mErrorSpriteList[UnityEngine.Random.Range(0, mErrorSpriteList.Count)];
        }
        return null;
    }
}
